// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common

GraphicsBox {
  id: root

  property var selected: []
  property int min
  property int max
  property string prompt
  property var generals
  property bool isSearching: false
  property var all_skills: []
  property var filtered_skills: []
  
  // 分页属性
  property int currentPage: 0
  property int pageSize: 20  // 每页显示20个技能
  property int totalPages: 1
  
  title.text: prompt === "" ? Lua.tr("$Choice") : Util.processPrompt(prompt)
  // width: Math.max(40 + Math.min(5, active_skills.count) * (88 + (generals ? 36 : 0)), 300) + 100
  width: Math.max(40 + 5 * (88 + (generals ? 36 : 0)), 300) + 100
  height: Math.max(60 + Math.min(32, active_skills.count) * 11, 270) + 150

  Item {
    id: searchBar
    anchors.top: parent.top
    anchors.topMargin: 40
    anchors.left: parent.left
    anchors.right: parent.right
    height: 40
    
    RowLayout {
      anchors.fill: parent
      anchors.margins: 10
      spacing: 10
      
      Text {
        text: Lua.tr("搜索: ")
        font.pixelSize: 16
        color: "#E4D5A0"
      }
      
      TextField {
        id: searchInput
        Layout.fillWidth: true
        placeholderText: Lua.tr("技能名/技能描述" + ( generals ? "/武将名" :"" ) + "...")
        verticalAlignment: TextInput.AlignVCenter
        background: Rectangle {
          color: "#88EEEEEE"
          radius: 5
        }
        
        onTextChanged: {
          if (text.length > 0) {
            filterSkills(text);
            root.isSearching = true;
          } else {
            resetSkills();
            root.isSearching = false;
          }
        }
      }
      
      ToolButton {
        text: Lua.tr("清空×")
        enabled: searchInput.text.length > 0
        onClicked: {
          searchInput.text = "";
          resetSkills();
          root.isSearching = false;
        }
        background: Rectangle {
          color: "#88EEEEEE"
          radius: 5
        }
      }
    }
  }

  Flickable {
    id: skillsFlickable
    ScrollBar.vertical: ScrollBar {
      policy: ScrollBar.AlwaysOn
    }
    flickableDirection: Flickable.VerticalFlick
    
    anchors.top: searchBar.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: pageControls.top
    anchors.margins: 10
    
    contentWidth: skillsList.width
    contentHeight: skillsList.height
    clip: true

    GridLayout {
      id: skillsList
      width: skillsFlickable.width - 20
      columns: 5
      rowSpacing: 10
      columnSpacing: 10
      
      Repeater {
        id: skill_buttons
        model: ListModel {
          id: active_skills
        }

        RowLayout {
          Avatar {
            id: avatarPic
            visible: _general != ""
            Layout.preferredHeight: 36
            Layout.preferredWidth: 36
            general: _general
          }

          SkillButton {
            id: skillBtn
            skill: Lua.tr(name)
            type: "active"
            enabled: true
            orig: name
            width: 88
            height: 36
            
            onPressedChanged: {
              if (pressed) {
                root.selected.push(this);
              } else {
                root.selected.splice(root.selected.findIndex(item => item.orig === orig), 1);
              }
              while (root.selected.length > max) {
                root.selected[0].pressed = false;
                //root.selected.splice(0,1);
              }
              root.updateSelectable();
            }
          }
        }
      }
    }
  }

  // 分页控件
  Item {
    id: pageControls
    anchors.bottom: buttonArea.top
    anchors.left: parent.left
    anchors.right: parent.right
    height: 40
    
    Row {
      anchors.centerIn: parent
      spacing: 15
      
      MetroButton {
        id: prevPageBtn
        text: Lua.tr("上一页")
        width: 80
        height: 30
        enabled: currentPage > 0
        onClicked: {
          currentPage--;
          updateCurrentPage();
        }
      }
      
      Text {
        id: pageInfo
        text: Lua.tr("第 %1 页 / 共 %2 页").arg(currentPage + 1).arg(totalPages)
        color: "#E4D5A0"
        font.pixelSize: 16
        verticalAlignment: Text.AlignVCenter
        height: 30
      }
      
      MetroButton {
        id: nextPageBtn
        text: Lua.tr("下一页")
        width: 80
        height: 30
        enabled: currentPage < totalPages - 1
        onClicked: {
          currentPage++;
          updateCurrentPage();
        }
      }
      
      // 修复的每页显示数量选择器
      Rectangle {
        id: pageSizeSelector
        width: 140
        height: 30
        color: "#88EEEEEE"
        radius: 5
        
        RowLayout {
          anchors.centerIn: parent
          //anchors.margins: -5
          
          Text {
            text: Lua.tr("   每页:")
            font.pixelSize: 14
            verticalAlignment: Text.AlignVCenter
            height: 30
          }
          
          Button {
            id: pageSizeButton
            Layout.fillWidth: true
            background: Rectangle {
              color: "transparent"
            }
            
            contentItem: Text {
              text: pageSize + " " + Lua.tr("项") + "    ▾"
              font.pixelSize: 14
              verticalAlignment: Text.AlignVCenter
              horizontalAlignment: Text.AlignHCenter
              height: 30
            }
            
            onClicked: {
              // 显示下拉菜单
              pageSizeMenu.popup()
            }
          }
          
          Menu {
            id: pageSizeMenu
            width: pageSizeButton.width
            
            MenuItem {
              text: "10 " + Lua.tr("项")
              onTriggered: setPageSize(10)
            }
            
            MenuItem {
              text: "20 " + Lua.tr("项")
              onTriggered: setPageSize(20)
            }
            
            MenuItem {
              text: "30 " + Lua.tr("项")
              onTriggered: setPageSize(30)
            }
            
            MenuItem {
              text: "50 " + Lua.tr("项")
              onTriggered: setPageSize(50)
            }
          }
        }
      }
    }
  }

  Item {
    id: buttonArea
    anchors.bottom: parent.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    height: 50
    
    Row {
      anchors.centerIn: parent
      spacing: 15
      
      MetroButton {
        id: buttonConfirm
        text: Lua.tr("OK")
        width: 120
        height: 35
        enabled: false
        
        onClicked: {
          close();
          roomScene.state = "notactive";
          ClientInstance.replyToServer("", JSON.stringify(root.selected.map(item => item.orig)));
        }
      }

      MetroButton {
        id: buttonCancel
        text: Lua.tr("Cancel")
        width: 120
        height: 35
        
        onClicked: {
          close();
          roomScene.state = "notactive";
          ClientInstance.replyToServer("", "");
        }
      }
      
      MetroButton {
        id: detailBtn
        width: 180
        height: 35
        text: Lua.tr("查看技能")
        
        onClicked: {
          let _skills = [];
          if (root.selected.length > 0) {
            _skills = root.selected.map(item => item.orig);
          } else {
            for (let i = 0; i < active_skills.count; i++){
              _skills.push(active_skills.get(i).name);
            }
          }
          roomScene.startCheatByPath("packages/utility/qml/SkillDetail", { skills: _skills });
        }
      }
    }
  }

  function setPageSize(size) {
    pageSize = size;
    updateTotalPages();
    
    // 如果当前页超过总页数，跳转到最后一页
    if (currentPage >= totalPages) {
      currentPage = totalPages > 0 ? totalPages - 1 : 0;
    }
    updateCurrentPage();
  }

  function filterSkills(text) {
    const searchText = text.toLowerCase();
    filtered_skills = [];
    
    for (let i = 0; i < all_skills.length; i++) {
      const skillObj = all_skills[i];
      if (Lua.tr(skillObj.name).toLowerCase().indexOf(searchText) !== -1 || Lua.tr(":"+skillObj.name).toLowerCase().indexOf(searchText) !== -1 
      || Lua.tr(skillObj._general).toLowerCase().indexOf(searchText) !== -1 ) {
        filtered_skills.push(skillObj);
      }
    }
    
    // 重置分页
    currentPage = 0;
    updateTotalPages();
    updateCurrentPage();
    
    // 清空选择
    root.selected = [];
    root.updateSelectable();
  }
  
  function resetSkills() {
    // 重置为全部技能
    filtered_skills = all_skills.slice();
    
    // 重置分页
    currentPage = 0;
    updateTotalPages();
    updateCurrentPage();
    
    // 清空选择
    root.selected = [];
    root.updateSelectable();
  }
  
  function updateTotalPages() {
    totalPages = Math.ceil(filtered_skills.length / pageSize);
    if (totalPages === 0) totalPages = 1;
  }
  
  function updateCurrentPage() {
    active_skills.clear();
    
    const startIndex = currentPage * pageSize;
    const endIndex = Math.min(startIndex + pageSize, filtered_skills.length);
    
    for (let i = startIndex; i < endIndex; i++) {
      active_skills.append(filtered_skills[i]);
    }
  }

  function updateSelectable() {
    buttonConfirm.enabled = (selected.length <= max && selected.length >= min);
  }

  function loadData(data) {
    let skills, i;
    [skills, min, max, prompt, generals] = data;
    
    // 保存所有技能用于搜索
    all_skills = [];
    
    if (!generals) {
      for (i = 0; i < skills.length; i++) {
        const skillObj = { name: skills[i], _general: "" };
        all_skills.push(skillObj);
      }
    } else {
      for (i = 0; i < skills.length; i++) {
        const skillObj = { name: skills[i], _general: generals[i] ?? "" };
        all_skills.push(skillObj);
      }
    }
    
    // 初始化搜索状态
    searchInput.text = "";
    root.isSearching = false;
    
    // 初始化分页
    filtered_skills = all_skills.slice();
    updateTotalPages();
    updateCurrentPage();
    updateSelectable();
  }
}